package com.wang.user.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.exception.BusinessException;
import com.wang.reponse.EvaluationReplyVo;
import com.wang.reponse.UserVo;
import com.wang.user.mapper.EvaluationReplyMapper;
import com.wang.user.model.EvaluationReply;
import com.wang.user.model.User;
import com.wang.user.service.EvaluationReplyService;
import com.wang.user.service.user.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 评价回复服务实现类
 */
@Service
public class EvaluationReplyServiceImpl extends ServiceImpl<EvaluationReplyMapper, EvaluationReply>
        implements EvaluationReplyService {

    @Resource
    private UserService userService;

    @Resource
    private EvaluationReplyMapper evaluationReplyMapper;

    @Override
    public Boolean submit(EvaluationReply reply) {
        User loginUser = userService.getLoginUser();
        
        EvaluationReply newReply = new EvaluationReply();
        BeanUtils.copyProperties(reply, newReply);
        newReply.setUserId(loginUser.getUid());
        return save(newReply);
    }

    @Override
    public Boolean deleteById(Long id) {
        EvaluationReply reply = getById(id);
        if (reply == null) {
            throw new BusinessException("回复不存在");
        }
        return removeById(id);
    }

    @Override
    public List<EvaluationReply> getByEvaluationId(Long evaluationId) {
        return commonGetByEvaluationId(evaluationId);
    }

    private List<EvaluationReply> commonGetByEvaluationId(Long evaluationId){
        List<EvaluationReply> allReplies = evaluationReplyMapper.listByEvaluationId(evaluationId);
        if (allReplies.isEmpty()) {
            return new ArrayList<>();
        }

        // 构建回复树
        Map<Long, List<EvaluationReply>> parentReplyMap = allReplies.stream()
                .collect(Collectors.groupingBy(reply -> reply.getParentReplyId() == null ? 0L : reply.getParentReplyId()));

        // 获取顶级回复（parentReplyId为null的回复）
        List<EvaluationReply> rootReplies = parentReplyMap.getOrDefault(0L, new ArrayList<>());

        // 递归设置子回复
        rootReplies.forEach(reply -> setChildren(reply, parentReplyMap));

        return rootReplies;
    }

    @Override
    public List<EvaluationReplyVo> getVoByEvaluationId(Long evaluationId) {
        List<EvaluationReply> replies = commonGetByEvaluationId(evaluationId);
        if (replies.isEmpty()) {
            return new ArrayList<>();
        }
        return replies.stream().map(this::setReplyUserInfo).collect(Collectors.toList());
    }

    private EvaluationReplyVo setReplyUserInfo(EvaluationReply reply){
        EvaluationReplyVo replyVo = new EvaluationReplyVo();
        BeanUtils.copyProperties(reply, replyVo);
        User replyUser = userService.getById(reply.getUserId());
        if (replyUser != null) {
            UserVo replyUserVo = new UserVo();
            BeanUtils.copyProperties(replyUser, replyUserVo);
            replyVo.setUser(replyUserVo);

            // 设置子回复的用户信息
            if (CollectionUtil.isNotEmpty(reply.getChildren())) {
                List<EvaluationReplyVo> childReplyVos = reply.getChildren().stream()
                        .map(this::setReplyUserInfo)
                        .collect(Collectors.toList());
                replyVo.setChildren(childReplyVos);
            }
        }
        return replyVo;
    }

    /**
     * 递归设置子回复
     * @param parent 父回复
     * @param parentReplyMap 父回复ID到子回复列表的映射
     */
    private void setChildren(EvaluationReply parent, Map<Long, List<EvaluationReply>> parentReplyMap) {
        List<EvaluationReply> children = parentReplyMap.get(parent.getId());
        if (children != null && !children.isEmpty()) {
            // 对子回复按创建时间排序
            children.sort(Comparator.comparing(EvaluationReply::getCreateTime));
            // 设置子回复
            parent.setChildren(children);
            // 递归处理每个子回复的子回复
            children.forEach(child -> setChildren(child, parentReplyMap));
        } else {
            // 如果没有子回复，设置为空列表
            parent.setChildren(new ArrayList<>());
        }
    }
} 